﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using System.IO;
using EvePoint.Library.HtmlControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace EvePoint.UI
{
    public class ViewportSettings : Microsoft.SharePoint.WebControls.LayoutsPageBase
    {

        #region Protected Fields


        protected RadioButtonList UserScalableRBL;
        protected RadioButtonList UseDeviceSizingRBL; 
        protected Button OKBtn;

        protected TextBox InitialScaleTxtBox;
        protected TextBox MinimumScaleTxtBox;
        protected TextBox MaximumScaleTxtBox;
        protected TextBox WidthTxtBox;
        protected TextBox HeightTxtBox;

        protected RangeValidator WidthRangeValidator;
        protected RangeValidator HeightRangeValidator;
        protected RangeValidator InitialScaleRangeValidator;
        protected RangeValidator MinScaleRangeValidator;
        protected RangeValidator MaxScaleRangeValidator; 

        #endregion 


        #region Page Event Methods


        protected void Page_Load(object sender, EventArgs e)
        {
            //Set up Range Validator Properties. 

            WidthRangeValidator.MinimumValue = EvePoint.Library.HtmlControls.Viewport.MINVIEWPORTWIDTH.ToString(); 
            WidthRangeValidator.MaximumValue = EvePoint.Library.HtmlControls.Viewport.MAXVIEWPORTWIDTH.ToString();

            WidthRangeValidator.ErrorMessage = string.Format("Please enter a Viewport Width between {0} and {1}.", EvePoint.Library.HtmlControls.Viewport.MINVIEWPORTWIDTH, EvePoint.Library.HtmlControls.Viewport.MAXVIEWPORTWIDTH);

            HeightRangeValidator.MinimumValue = EvePoint.Library.HtmlControls.Viewport.MINVIEWPORTWHEIGHT.ToString();
            HeightRangeValidator.MaximumValue = EvePoint.Library.HtmlControls.Viewport.MAXVIEWPORTHEIGHT.ToString();

            HeightRangeValidator.ErrorMessage = string.Format("Please enter a Viewport Height between {0} and {1}.", EvePoint.Library.HtmlControls.Viewport.MINVIEWPORTWHEIGHT, EvePoint.Library.HtmlControls.Viewport.MAXVIEWPORTHEIGHT); 

            InitialScaleRangeValidator.MinimumValue = EvePoint.Library.HtmlControls.Viewport.MINSCALE.ToString();
            InitialScaleRangeValidator.MaximumValue = EvePoint.Library.HtmlControls.Viewport.MAXSCALE.ToString();

            MinScaleRangeValidator.MinimumValue = EvePoint.Library.HtmlControls.Viewport.MINSCALE.ToString();
            MinScaleRangeValidator.MaximumValue = EvePoint.Library.HtmlControls.Viewport.MAXSCALE.ToString();

            MaxScaleRangeValidator.MinimumValue = EvePoint.Library.HtmlControls.Viewport.MINSCALE.ToString();
            MaxScaleRangeValidator.MaximumValue = EvePoint.Library.HtmlControls.Viewport.MAXSCALE.ToString();

            if (!IsPostBack)
            {
                DeserializeSettings(); 
            }
        }



        #endregion 

        #region Event Methods





        protected void OKBtn_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {

                SerializeSettings();

                SPUtility.Redirect("settings.aspx", SPRedirectFlags.RelativeToLocalizedLayoutsPage, System.Web.HttpContext.Current);


            }

        }

        #endregion 


        #region Helper Methods

        private void DeserializeSettings()
        {
            SPWeb currentWeb = SPContext.Current.Web;

            if (currentWeb != null)
            {
                string serializedSPViewport = currentWeb.Properties[EvePoint.Library.HtmlControls.SPViewport.PROPERTYBAGKEY];

                if (!string.IsNullOrEmpty(serializedSPViewport))
                {



                    XmlSerializer serializer = new XmlSerializer(typeof(ViewportProperties));

                    using (StringReader sReader = new StringReader(serializedSPViewport))
                    {
                        ViewportProperties viewport = (ViewportProperties)serializer.Deserialize(sReader);

                      

                        //Set Text Boxes 
                        if (viewport.InitialScale.HasValue)
                        {
                            InitialScaleTxtBox.Text = viewport.InitialScale.Value.ToString();
                        }

                        if (viewport.Width.HasValue)
                        {
                            WidthTxtBox.Text = viewport.Width.Value.ToString(); 
                        }

                        if(viewport.Height.HasValue)
                        {
                            HeightTxtBox.Text=viewport.Height.Value.ToString(); 
                        }

                        if (viewport.MaximumScale.HasValue)
                        {
                            MaximumScaleTxtBox.Text = viewport.MaximumScale.Value.ToString(); 
                        }
                       
                         if(viewport.MinimumScale.HasValue)
                         {
                             MinimumScaleTxtBox.Text = viewport.MinimumScale.Value.ToString(); 
                         }
                     

                        //Set Radio Button Lists. 

                        if(viewport.UseDeviceHeightAndWidth.HasValue)
                        {
                            if (viewport.UseDeviceHeightAndWidth.Value)
                            {
                                try
                                {
                                    UseDeviceSizingRBL.SelectedValue = "1";
                                }

                                catch
                                {
                                    //TODO: ULS Logging Pluggable
                                }
                            }
                            else
                            {
                                try
                                {
                                    UseDeviceSizingRBL.SelectedValue = "0";
                                }

                                catch
                                {
                                    //TODO: ULS Logging Pluggable
                                }
                            }


                        }

                        
                        if( viewport.UserScalable.HasValue)
                        {
                            if(viewport.UserScalable.Value)
                            {
                                try
                                {
                                    UserScalableRBL.SelectedValue = "1"; 
                                }
                                catch
                                {
                                      //TODO: ULS Logging Pluggable
                                }
                              

                            }

                            else
                            {
                                try
                                {
                                UserScalableRBL.SelectedValue = "0";
                                }
                                catch
                                {
                                    //TODO: ULS Logging Pluggable
                                }
                                
                            }

                        }
                        

                    }
                }
            }

        }


        private void SerializeSettings()
        {



            XmlSerializer serializer = new XmlSerializer(typeof(ViewportProperties));


            ViewportProperties vwport = GetViewport();

            using (StringWriter sWriter = new StringWriter())
            {
                serializer.Serialize(sWriter, vwport);

                string serializedObject=sWriter.ToString();


                if (!string.IsNullOrEmpty(serializedObject))
                {
                    SPWeb currentWeb = SPContext.Current.Web;


                    if (currentWeb != null)
                    {
                        try
                        {
                            currentWeb.Properties[EvePoint.Library.HtmlControls.SPViewport.PROPERTYBAGKEY] = serializedObject;
                            currentWeb.Properties.Update(); 
                        }

                        catch
                        {

                            //TODO: ULS Logging 
                        }


                    }

                }


            }

        }


        /// <summary>
        /// Returns viewport object with properties per this settings page. 
        /// </summary>
        /// <returns></returns>
        private ViewportProperties GetViewport()
        {
            ViewportProperties serializationObject = new ViewportProperties();


            if (!string.IsNullOrEmpty(UseDeviceSizingRBL.SelectedValue))
            {

                if (UseDeviceSizingRBL.SelectedValue.Equals("1"))
                {
                    serializationObject.UseDeviceHeightAndWidth = true;
                }
                else
                {
                    serializationObject.UseDeviceHeightAndWidth = false;
                }
            }

            if (!string.IsNullOrEmpty(UserScalableRBL.SelectedValue))
            {
                if (UserScalableRBL.SelectedValue.Equals("1"))
                {
                    serializationObject.UserScalable = true;
                }
                else
                {
                    serializationObject.UserScalable = false;
                }

            }


            if (!string.IsNullOrEmpty(WidthTxtBox.Text))
            {
                int width;

                if (int.TryParse(WidthTxtBox.Text, out width))
                {
                    serializationObject.Width = width;

                }
            }




            if (!string.IsNullOrEmpty(HeightTxtBox.Text))
            {

                int height;

                if (int.TryParse(HeightTxtBox.Text, out height))
                {
                    serializationObject.Height = height;
                }
            }



            if (!string.IsNullOrEmpty(MaximumScaleTxtBox.Text))
            {

                decimal maxScale;

                if (decimal.TryParse(MaximumScaleTxtBox.Text, out maxScale))
                {
                    serializationObject.MaximumScale = maxScale;
                }
            }



            if (!string.IsNullOrEmpty(MinimumScaleTxtBox.Text))
            {

                decimal minimumScale;

                if (decimal.TryParse(MinimumScaleTxtBox.Text, out minimumScale))
                {
                    serializationObject.MinimumScale = minimumScale;
                }
            }


            if (!string.IsNullOrEmpty(InitialScaleTxtBox.Text))
            {

                decimal initialScale;

                if (decimal.TryParse(InitialScaleTxtBox.Text, out initialScale))
                {
                    serializationObject.InitialScale = initialScale;
                }
                else
                {
                    //TODO: throw exception, ULS Logging, ditto for conditional statements above. 
                }
            }


            return serializationObject; 

        }

        #endregion 

    }


}
